<template>
  <div class="login-container">
    <div class="login-form">
      <div class="login-header">
        <h2>CRM客户关系管理系统</h2>
        <p>欢迎登录</p>
      </div>
      
      <el-form 
        ref="loginFormRef"
        :model="loginForm" 
        :rules="loginRules"
        class="login-form-content"
        @keyup.enter="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            size="large"
            prefix-icon="User"
            clearable
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            size="large"
            prefix-icon="Lock"
            show-password
            clearable
          />
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            size="large" 
            class="login-button"
            :loading="loading"
            @click="handleLogin"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>
      
      <div class="login-footer">
        <p>默认管理员账号：admin / 123456</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import { useLifecycle } from '@/utils/lifecycle'

const router = useRouter()
const userStore = useUserStore()
const { checkMounted, safeRef, safeAsync } = useLifecycle()

// 响应式数据
const loading = ref(false)
const loginFormRef = ref()

// 登录表单数据
const loginForm = reactive({
  username: '',
  password: '',
})

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

// 处理登录
const handleLogin = async () => {
  await safeAsync(async () => {
    // 使用safeRef安全访问ref
    const formRef = safeRef(loginFormRef)
    if (!formRef) {
      console.warn('登录表单引用不存在')
      return
    }
    
    await formRef.validate()
    
    if (!checkMounted()) return
    loading.value = true
    
    await userStore.login({
      username: loginForm.username,
      password: loginForm.password
    })
    
    if (!checkMounted()) return
    ElMessage.success('登录成功')
    router.push('/dashboard')
  }, (error) => {
    console.error('登录失败:', error)
    if (checkMounted()) {
      ElMessage.error(error.message || '登录失败，请检查用户名和密码')
      loading.value = false
    }
  })
  
  if (checkMounted()) {
    loading.value = false
  }
}

// 页面加载时的处理
onMounted(() => {
  // 如果已经登录，直接跳转到首页
  if (userStore.token) {
    router.replace('/dashboard')
    return
  }
  
  // 模拟登录，预填表单
  loginForm.username = 'admin'
  loginForm.password = '123456'
})

</script>

<style lang="scss" scoped>
.login-container {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  
  .login-form {
    width: 100%;
    max-width: 400px;
    background: rgba(255, 255, 255, 0.95);
    border-radius: 16px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    backdrop-filter: blur(8px);
    padding: 40px;
    
    .login-header {
      text-align: center;
      margin-bottom: 40px;
      
      h2 {
        color: #333;
        font-size: 24px;
        font-weight: 600;
        margin-bottom: 8px;
      }
      
      p {
        color: #666;
        font-size: 16px;
      }
    }
    
    .login-form-content {
      .el-form-item {
        margin-bottom: 24px;
      }
      
      .login-button {
        width: 100%;
        font-size: 16px;
        font-weight: 600;
        border-radius: 8px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border: none;
        
        &:hover {
          background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
        }
      }
    }
    
    .login-footer {
      margin-top: 30px;
      padding-top: 20px;
      border-top: 1px solid #eee;
      font-size: 12px;
      color: #666;
      text-align: center;
      
      p {
        margin: 4px 0;
        
        &:first-child {
          font-weight: 600;
          margin-bottom: 8px;
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 480px) {
  .login-container {
    padding: 15px;
    
    .login-form {
      padding: 30px 20px;
      
      .login-header {
        margin-bottom: 30px;
        
        h2 {
          font-size: 20px;
        }
        
        p {
          font-size: 14px;
        }
      }
    }
  }
}
</style> 